/** mutations
 * 获取state获取方法，不用在Mutations中写入，下方会自动遍历自动生成对应的setXxx方法。
 * 自定义mutations方法，正常写入即可。
 * 格式为：set + state名字（小驼峰格式）如：setFun
 */

import {createStore} from "vuex";
import {moduleA} from "./modules/moduleA";
import {getTokenInfo, setTokenInfo} from "../utils/token";
import {getThemeMediaInfo} from "../utils/themeMedia";

const state = {
    token: getTokenInfo() || {}, // 获取token  如果getToken没有token值 转换为空对象   短路运算
    themeMedia:getThemeMediaInfo() || false, // 主题色 true --light;false --dark
    count: 1,
}

const mutations = {
    // 设置token
    setToken(state: any, payload: any) {
        state.token = payload
        setTokenInfo(payload)
    },
    // 数量加减
    changeCount(state: any, payload: any) {
        state.count = state.count + payload
    },
}

const actions = {
    // 异步数量加减
    async changeCountAsync({commit}:any, preload:any) {
        setTimeout(()=>{
            commit('changeCount',preload)
        },1000)
    }
}

const getters = {}

const modules = {
    moduleA
}


/** 为state默认生成mutations方法*/
const defMutationsFun = (state:any,mutations:any)=>{
    for (let key in state) {
        let name = 'set' + key.replace(/^./, key[0].toUpperCase());
        // @ts-ignore
        if (name && !Reflect.has(mutations, name)) mutations[name] = (state, payload) => state[key] = payload
    }
}
// 设置 全局
defMutationsFun(state,mutations)
// 设置 modules
Object.keys(modules).forEach((key)=>{
    // @ts-ignore
    let {state,mutations} = modules[key]
    defMutationsFun(state,mutations)
})

export default createStore({state, mutations, actions, getters, modules})